<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <BasicTable
          @register="registerTable"
          :columns="columns"
          :dataSource="tableData"
          :canResize="false"
          :showIndexColumn="false"
          :striped="true"
          :bordered="true"
          :pagination="false"
          :actionColumn="hasPermission(['3-3-edit', '3-3-del']) ? actionColumn : undefined"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action' && hasPermission(['3-3-edit', '3-3-del'])">
              <TableAction
                :actions="[
                  {
                    label: '编辑',
                    icon: 'ant-design:edit-outlined',
                    ifShow: hasPermission('3-3-edit'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleEdit(record);
                    },
                  },
                  {
                    label: '删除',
                    icon: 'ant-design:delete-outlined',
                    ifShow: hasPermission('3-3-del'),
                    onClick: (e) => {
                      e.stopPropagation();
                      handleDelete(record);
                    },
                  },
                ]"
              />
            </template>
          </template>
          <template #toolbar>
            <a-input-search
              v-model:value="searchValue"
              placeholder="请输入搜索的编码/名称"
              style="width: 300px"
              :allowClear="true"
              @search="onSearch"
            />
            <a-button
              type="primary"
              @click="handleShowSelect"
              v-if="hasPermission('3-3-mesAddress')"
            >
              MES地址配置
            </a-button>
            <a-button
              type="primary"
              @click="throttleSyncMesData"
              :loading="loadingByBtn"
              v-if="hasPermission('3-3-mesSynchronize')"
            >
              同步MES数据
            </a-button>
            <a-button type="primary" @click="handleAdd" v-if="hasPermission('3-3-add')">
              新增
            </a-button>
            <a-button type="primary" @click="openModalByupload" v-if="hasPermission('3-3-upload')">
              导入
            </a-button>
            <!-- <BasicUpload
              v-if="hasPermission('3-3-upload')"
              :maxSize="50"
              :maxNumber="1"
              :api="uploadApi"
              :isShowThumb="false"
              :uploadParams="uploadParams"
              :showPreviewNumber="false"
              :emptyHidePreview="true"
              :accept="['.xlsx', '.xls']"
            /> -->
            <a-button type="primary" @click="handleAdd" v-if="hasPermission('3-3-import')">
              导出
            </a-button>
          </template>
        </BasicTable>
        <div class="flex py-2 items-center justify-end pagination-box">
          <a-pagination
            :show-total="(total) => `共 ${total} 条数据`"
            showSizeChanger
            size="small"
            :current="paginationInfo.data.current"
            :pageSize="paginationInfo.data.pageSize"
            :total="paginationInfo.data.total"
            @change="handlePageChange"
          />
        </div>
      </div>
    </div>
    <!-- 新增或编辑的弹窗 -->
    <modelByDetail
      :info="detailForm"
      @register="registerByDetail"
      @submit-success="handelUpateTable"
    />
    <!-- 上传Excel -->
    <uploadExcel
      @register="registerByUpload"
      :classParams="['SuperX.DeviceService.DeviceType.Model.DeviceTypeInfo,CQ.IOT.DeviceService']"
      :uploadParams="{
        Controller: 'Device',
        Action: 'FileImport',
        Parameters: Parameters,
        model: 'SuperX.DeviceService.DeviceType.Model.DeviceTypeInfo,CQ.IOT.DeviceService',
        sheetIndex: '-1',
        headRow: '0',
      }"
      @success="handleUploadSuccess"
    />
    <modelBySelect @register="registerBySelect" @submit-success="handelSuccessBySelect" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted, reactive, h } from 'vue';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { Pagination } from 'ant-design-vue';
  // import { BasicUpload } from '/@/components/Upload';
  // import { uploadApi } from '/@/api/system/index';
  import modelByDetail from '/@/views/project/equipmentType/components/modelByDetail.vue';
  import modelBySelect from '/@/views/project/equipmentLedger/components/modelBySelect.vue';
  import uploadExcel from '/@/components/uploadExcel/index.vue';
  import { deldevicetype, getdevicetypes, updateequipments } from '/@/api/equipmentType/index';
  import { useDebounceFn } from '@vueuse/core';

  const throttleSyncMesData = useDebounceFn(handleSyncMesData, 500);
  const APagination = Pagination;
  const { t } = useI18n();
  const { hasPermission } = usePermission();
  let loading = ref(false);
  let loadingByBtn = ref(false);
  let searchValue = ref('');
  let tableData = reactive([]);
  let Parameters = '[""]';
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });
  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '编码',
      dataIndex: 'Code',
    },
    {
      title: '名称',
      dataIndex: 'Name',
    },
  ];
  // 操作栏
  let actionColumn = {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  let detailForm = reactive({
    type: 'add',
    data: {},
  });

  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerByUpload, { openModal: openModalByupload, closeModal: closeModalByupload }] =
    useModal();
  const [registerBySelect, { openModal: openModalBySelect, closeModal: closeModalBySelect }] =
    useModal();
  const [registerTable] = useTable();
  const { createConfirm, createMessage } = useMessage();
  // 上传成功
  function handleUploadSuccess() {
    closeModalByupload();
    searchValue.value = '';
    paginationInfo.data.current = 1;
    getTableData();
  }
  // 搜索方法
  function onSearch() {
    paginationInfo.data.current = 1;
    getTableData();
  }
  // 获取设备类型
  async function getTableData() {
    try {
      loading.value = true;
      let CategoryObj = {
        1: '生产设备',
        2: '检测设备',
        3: '辅助设备',
        4: '厂务设备',
        5: '仪器仪表',
        6: '办公设备',
        7: ' IT设备',
        8: '其它',
      };
      let res = await getdevicetypes([
        {
          PageNO: paginationInfo.data.current,
          SearchTypeName: searchValue.value ? searchValue.value : '',
          SearchCategory: 0,
          PageSize: paginationInfo.data.pageSize,
        },
      ]);
      paginationInfo.data.total = res.TotalRows;
      tableData = res.Rows.map((item) => {
        item.CategoryCn = CategoryObj[item.Category];
        return item;
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 新增或编辑成功事件
  function handelUpateTable() {
    detailForm.type = 'add';
    detailForm.data = {};
    closeModalByDetail();
    getTableData();
  }
  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  // 新增
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = {};

    openModalByDetail();
  }

  // 编辑
  function handleEdit(params) {
    detailForm.type = 'update';
    detailForm.data = params;

    openModalByDetail();
  }
  // 删除
  function handleDelete(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该设备（${params.TypeName}）`),
      onOk: async () => {
        loading.value = true;
        try {
          await deldevicetype([params]);
          searchValue.value = '';
          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      },
    });
  }
  // 显示MES地址下拉框弹窗
  function handleShowSelect() {
    openModalBySelect();
  }
  function handelSuccessBySelect() {
    closeModalBySelect();
  }
  // 同步mes数据
  async function handleSyncMesData() {
    loadingByBtn.value = true;
    try {
      await updateequipments([]);
      getTableData();
      createMessage.success('同步成功');
      loadingByBtn.value = false;
    } catch (error) {
      loadingByBtn.value = false;
    }
  }
  onMounted(async () => {
    getTableData();
  });
</script>

<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .tag::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }
</style>
